<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\CreateOrderRequest;
use App\Http\Requests\UpdateOrderRequest;
use App\Models\Address;
use App\Models\Goods;
use App\Models\GoodsAttribute;
use App\Models\Order;
use App\Models\OrderGoods;
use App\Models\PayRecord;
use App\Models\ReturnLog;
use App\Repositories\OrderRepository;
use App\Http\Controllers\AppBaseController;
use App\User;
use EasyWeChat\Foundation\Application;
use Illuminate\Http\Request;
use Flash;
use Illuminate\Support\Facades\DB;
use Prettus\Repository\Criteria\RequestCriteria;
use Response;

class OrderController extends AppBaseController
{
    /** @var  OrderRepository */
    private $orderRepository;

    public function __construct(OrderRepository $orderRepo)
    {
        $this->orderRepository = $orderRepo;
    }

    /**
     * Display a listing of the Order.
     *
     * @param Request $request
     * @return Response
     */
    public function index(Request $request)
    {
        $model = new Order();
        $status = request('status',100);
        if($status && $status!=100){
            $model = $model->where('status',$status);
        }

        $user_id = request('user_id',false);
        if($user_id){
            $model = $model->where('user_id',$user_id);
        }

        $sn = request('sn',false);
        if($sn){
            $model = $model->where('sn',$sn);
        }
        $openid = request('openid',false);
        if($openid){
            $user = User::where('openid', $openid)->first();
            if($user){
                $model = $user->orders();
            }else{
                $model = $model->where('id',0);
            }
        }
        $nickname = request('nickname',false);
        if($nickname){
            $user = User::where('nickname', 'like', "%$nickname%")->first();
            if($user){
                $model = $user->orders();
            }else{
                $model = $model->where('id',0);
            }
        }
        $take_name = request('take_name',false);
        $take_phone = request('take_phone',false);
        $take_address = request('take_address',false);
        if($take_name || $take_phone || $take_address){
            $addresses = new Address();
            if($take_name)
                $addresses = $addresses->where('name', 'like', "%$take_name%");
            if($take_phone)
                $addresses = $addresses->where('phone', 'like', "%$take_phone%");
            if($take_address)
                $addresses = $addresses->where('address', 'like', "%$take_address%");
            $addresses = $addresses->get();
            $address_arr = [];
            foreach ($addresses as $address) {
                $address_arr[] = $address->id;
            }
            if(empty($address_arr)){
                $model = $model->where('id',0);
            }else{
                $model = $model->whereIn('address_id', $address_arr);
            }
        }
        $orders = $model->orderBy('id', 'desc')->paginate(20);
        $orders->load('goods');
        $orders->load('address');

        $goods_arr = [];
        $goods = Goods::all();
        foreach ($goods as $v) {
            $goods_arr[$v->id] = $v;
        }

        $attribute_arr = [];
        $attributes = GoodsAttribute::all();
        foreach ($attributes as $v) {
            $attribute_arr[$v->id] = $v;
        }
        return view('orders.index')
            ->with('orders', $orders)->with('attribute_arr', $attribute_arr)
            ->with('status', $status)
            ->with('goods_arr', $goods_arr)->with('request',$request->all());
    }

    /**
     * Show the form for creating a new Order.
     *
     * @return Response
     */
    public function create()
    {
        return view('orders.create');
    }

    /**
     * Store a newly created Order in storage.
     *
     * @param CreateOrderRequest $request
     *
     * @return Response
     */
    public function store(CreateOrderRequest $request)
    {
        $input = $request->all();

        $order = $this->orderRepository->create($input);

        Flash::success('Order saved successfully.');

        return redirect(route('orders.index'));
    }

    /**
     * Display the specified Order.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function orderInfo($id)
    {
        $order = $this->orderRepository->findWithoutFail($id);

        if (empty($order)) {
            Flash::error('Order not found');

            return redirect(route('orders.index'));
        }

        return view('orders.info')->with('order', $order)->with('title','订单详情');
    }
    public function show($id)
    {
        $order = $this->orderRepository->findWithoutFail($id);

        if (empty($order)) {
            Flash::error('Order not found');

            return redirect(route('orders.index'));
        }

        return view('orders.show')->with('order', $order);
    }

    /**
     * Show the form for editing the specified Order.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {
        $order = $this->orderRepository->findWithoutFail($id);

        if (empty($order)) {
            Flash::error('Order not found');

            return redirect(route('orders.index'));
        }

        return view('orders.edit')->with('order', $order);
    }

    /**
     * Update the specified Order in storage.
     *
     * @param  int              $id
     * @param UpdateOrderRequest $request
     *
     * @return Response
     */
    public function update($id, UpdateOrderRequest $request)
    {
        $order = $this->orderRepository->findWithoutFail($id);

        if (empty($order)) {
            Flash::error('Order not found');

            return redirect(route('orders.index'));
        }
        if($request->address_name || $request->address_address){
            $address = $order->address;
            $address->name = $request->address_name;
            $address->address = $request->address_address;
            $address->save();
        }
        $order = $this->orderRepository->update($request->all(), $id);

        Flash::success('Order updated successfully.');

        return redirect(route('orders.index'));
    }

    /**
     * Remove the specified Order from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        $order = $this->orderRepository->findWithoutFail($id);

        if (empty($order)) {
            Flash::error('Order not found');

            return redirect(route('orders.index'));
        }

        $this->orderRepository->delete($id);

        Flash::success('Order deleted successfully.');

        return redirect(route('orders.index'));
    }

    public function peisongdan($id)
    {
        $order = $this->orderRepository->findWithoutFail($id);

        if (empty($order)) {
            Flash::error('Order not found');

            return redirect(route('orders.index'));
        }
//        foreach ($order->goods as $good) {
//            dump($good->goods_id);
//            dump($good->attribute_id);
//            dump($good->goods->name);
//        }
        return view('orders.peisongdan')->with('order', $order)->with('title','订单详情');
    }

    public function shouhuo($id)
    {
        $order = $this->orderRepository->findWithoutFail($id);

        if (empty($order)) {
            Flash::error('Order not found');

            return redirect(route('orders.index'));
        }
        $order->status=4;
        $order->save();
        Flash::success('Order change successfully.');

        return redirect(route('orders.index'));
    }
    
    public function fahuozhong($id)
    {
        $order = $this->orderRepository->findWithoutFail($id);

        if (empty($order)) {
            Flash::error('Order not found');

            return redirect(route('orders.index'));
        }
        $order->status=3;
        $order->save();
        Flash::success('Order change successfully.');

        return redirect(route('orders.index'));
    }

    public function returnOk($id)
    {
//        $app = new Application(config('easywechat'));
//        $payment = $app->payment;
//        dd($payment->refund(2017092901314139,2017092901314132, 35.97*100,35.97*100));
        $log = ReturnLog::find($id);
        $order = $log->order;
        $attribute = $log->attribute;
        $old_jifen = $order->acquire_integral;
        $all_price = 0;
        $can_refund_price = $order->calculate_pay_price;
        if($log->type == 1){
            $order->status=12;
            foreach ($order->goods as $good) {
                if($good->status!=12){
                    $attribute = $good->attribute;
//                    if($attribute) {
//                        $price = getPrice($attribute);
//                    }else{
//                        $price = getPrice($good->goods);
//                    }
                    $price = $good->price;
                    $all_price += $price*$good->number;
                    //订单处理
                    $order = $this->orderRepository->orderCutPrice($order,$price*$good->number);
                    $order->calculate_goods_number -= $good->number;
                }
            }
        }else{
//            if($attribute){
//                $price = getPrice($attribute);
//            }else{
//                $price = getPrice($log->goods);
//            }
            $price = $log->price;
            $all_price += $price*$log->number;
            $order = $this->orderRepository->orderCutPrice($order,$price*$log->number);
            $order->calculate_goods_number -= $log->number;
            //通过订单下商品 判断订单状态是否改变
            $ok = 0;
            foreach ($order->goods as $g) {
                if($g->status==1)
                    $ok = 1;
            }
            if($ok==0){
                $order->status=12;
            }
        }

        //退款可获得的积分
        $c_jifen = $old_jifen - $order->acquire_integral;
        $refund_price = $all_price - $c_jifen/100;
        $refund_price = ($refund_price>$can_refund_price?$can_refund_price:$refund_price);
        //微信退款
        $wxpayRecord = PayRecord::where('trade_state', 'SUCCESS')->where('order_id',$order->id)->first();
        $app = new Application(config('easywechat'));
        $payment = $app->payment;
        $refund_no = date('Ymdhis', time()).substr(floor(microtime()*1000),0,1).rand(0,9);
        //-----------调试代码
//        dump($wxpayRecord->amount);
//        dd($payment->queryRefund($wxpayRecord->out_trade_no));
//        $refund_res = $payment->refund($wxpayRecord->out_trade_no,
//            $refund_no, $wxpayRecord->amount*100,10.21*100);
//        dd($refund_res);
        //------------
        if($refund_price>0){
            //订单剩余可以退的钱
            $wxpayRecord_residue = $wxpayRecord->amount - $wxpayRecord->return_amount;
            if($refund_price>$wxpayRecord_residue){
                //还需要别的订单退的钱
                $other_amount = $refund_price - $wxpayRecord_residue;
                if($other_amount>0){
                    //合并订单里退钱
                    $other_orders = Order::withTrashed()->where('merge_id',$order->id)->get();
                    foreach ($other_orders as $other_order) {
                        if ($other_amount > 0) {
                            $refund_no1 = date('Ymdhis', time()).substr(floor(microtime()*1000),0,1).rand(0,9);
                            //表示还可以退钱
                            if ($other_order->payRecord->return_amount < $other_order->payRecord->amount) {
                                //这个合并订单可以退的钱
                                $has_amount = $other_order->payRecord->amount - $other_order->payRecord->return_amount;
                                $other_amount = $has_amount - $other_amount;
                                //表示够退
                                if ($other_amount >= 0) {
                                    $other_order->payRecord->return_amount += $has_amount - $other_amount;
                                    $payment->refund($other_order->payRecord->out_trade_no,
                                        $refund_no1, $other_order->payRecord->amount * 100, ($has_amount - $other_amount) * 100);
                                    $other_amount = 0;
                                }
                                //不够退
                                else {
                                    $other_amount = -$other_amount;
                                    $other_order->payRecord->return_amount += $has_amount;
                                    $payment->refund($other_order->payRecord->out_trade_no,
                                        $refund_no1, $other_order->payRecord->amount * 100, $has_amount * 100);
                                }
                                $other_order->payRecord->save();
                            }
                        }
                    }
                }
                $refund_res = $payment->refund($wxpayRecord->out_trade_no,
                    $refund_no, $wxpayRecord->amount*100,$wxpayRecord_residue*100);
            }else{
                $wxpayRecord_residue = $refund_price;
                $refund_res = $payment->refund($wxpayRecord->out_trade_no,
                    $refund_no, $wxpayRecord->amount*100,$refund_price*100);
            }

            $refund_res = $refund_res->toArray();
        }else{
            $wxpayRecord_residue = 0;
            $refund_res['return_code'] = 'SUCCESS';
            $refund_res['result_code'] = 'SUCCESS';
        }
        if($refund_res['return_code']=='SUCCESS' && isset($refund_res['result_code']) && $refund_res['result_code']=='SUCCESS'){
            if($log->type==1){
                ReturnLog::where('order_id', $order->id)->update(['status'=>2]);
                OrderGoods::where('order_id',$log->order_id)->update(['status'=>12]);
            }else{
                $orderGoods = OrderGoods::find($log->orderGoods_id);
                $orderGoods->return_number += $log->number;
                $orderGoods->status = 12;
//                if($orderGoods->number>$log->number){
//                    $orderGoods->save();
//                }

                $orderGoods->save();
//                OrderGoods::where('order_id',$log->order_id)->where('goods_id',$log->goods->id)->update(['status'=>12]);
//                if($attribute){
//                    OrderGoods::where('order_id',$log->order_id)->where('attribute_id',$attribute->id)->update(['status'=>12]);
//                }else{
//                    OrderGoods::where('order_id',$log->order_id)->where('goods_id',$log->goods->id)->update(['status'=>12]);
//                }
            }
            if($wxpayRecord){
                $wxpayRecord->return_amount += $wxpayRecord_residue;
                $wxpayRecord->save();
            }
            $user = $order->user;
            $user->integral += $c_jifen;
            $user->save();
            $log->status = 2;
            $log->response = json_encode($refund_res,256);
            $log->save();
            $order->save();
            Flash::success('退款成功');
        }else{
            if(isset($refund_res))
                Flash::error($refund_res['err_code_des']);
            else
                Flash::error('退款金额不能为0');
        }
        return redirect(route('returnLogs.index'));
    }

    public function returnBar($id)
    {
        $log = ReturnLog::find($id);
        $order = $log->order;
        if($log->type == 1){
            $order->status=13;
            $order->save();
            ReturnLog::where('order_id', $order->id)->update(['status'=>3]);
        }else{
            $attribute = $log->attribute;
            if($attribute){
                OrderGoods::where('order_id',$log->order_id)->where('attribute_id',$attribute->id)->update(['status'=>13]);
            }else{
                OrderGoods::where('order_id',$log->order_id)->where('goods_id',$log->goods->id)->update(['status'=>13]);
            }
            if($log->orderGoods_id){
                $orderGoods = OrderGoods::find($log->orderGoods_id);
                if($orderGoods){
                    $orderGoods->apply_return_number -= $log->number;
                    $orderGoods->save();
                }
            }
            //通过订单下商品 判断订单状态是否改变
            $ok = 0;
            foreach ($order->goods as $g) {
                if($g->status==1)
                    $ok = 1;
            }
            if($ok==0){
                $order->status=13;
            }
        }
        $log->status = 3;
        $log->save();
        Flash::success('拒绝退款成功');

        return redirect(route('returnLogs.index'));
    }

    public function panel()
    {
        return view('orders.panel');
    }

    public function fresh()
    {
      return view('orders.fresh');
    }

    public function returnOrder()
    {
        $order_id = request('order_id', null);
        $order = Order::find($order_id);
        if($order) {
            $price = $order->pay_money;
            $num = $order->goods_num;
            foreach ($order->goods as $v) {
                if($v->status==11 && $v->status==12){
                    $num -= $v->number;
                    $price -= $v->price;
                }
            }
            if($order->status!='11'){
                $order->status=11;
                $order->save();
                ReturnLog::create([
                    'order_id'=>$order->id,
                    'type'=>1,
                    'num'=>$num,
                    'price'=>$price,
                    'status'=>1,
                ]);
            }
        }
        return redirect(route('orders.peisongdan',$order_id));
    }


    public function returnGoods()
    {
        $orderGoods_id = request('orderGoods_id', null);
        $order_id = request('order_id', null);
        $number = request('number', null);
        $order = Order::find($order_id);
        $orderGoods = OrderGoods::find($orderGoods_id);
        if(!$order_id || !$order){
            return redirect(route('orders.peisongdan',$order_id));
        }
        if(!$orderGoods_id || !$orderGoods){
            return redirect(route('orders.peisongdan',$order_id));
        }
        if($orderGoods->status!=11 and $orderGoods->status!=12) {
            $orderGoods->status = 11;
            $orderGoods->save();
            ReturnLog::create([
                'order_id' => $order->id,
                'type' => 2,
                'status' => 1,
                'price' => $orderGoods->price,
                'orderGoods_id' => $orderGoods->id,
                'goods_id' => $orderGoods->goods_id,
                'attribute_id' => $orderGoods->attribute_id,
                'number' => $number ? $number : $orderGoods->number,
            ]);
            $ok = 0;
            foreach ($order->goods as $g) {
                if ($g->status == 1)
                    $ok = 1;
            }
            if ($ok == 0) {
                $order->status = 11;
                $order->save();
            }
        }
        return redirect(route('orders.peisongdan',$order_id));
    }

}
